package algorithm;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.Enumeration;

/**
 * Created by yangshunxing on 2017/7/19.
 */
public class RsaAlgorithm {

    /**
     * 读取私钥  返回PrivateKey
     * @param path  包含私钥的证书路径
     * @param password  私钥证书密码
     * @return 返回私钥PrivateKey
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws CertificateException
     * @throws IOException
     * @throws UnrecoverableKeyException
     */
    private static PrivateKey getPrivateKey(String path, String password)
            throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        FileInputStream fis = new FileInputStream(path);
        char[] nPassword = null;
        if ((password == null) || password.trim().equals("")) {
            nPassword = null;
        } else {
            nPassword = password.toCharArray();
        }
        ks.load(fis, nPassword);
        fis.close();
        Enumeration<String> en = ks.aliases();
        String keyAlias = null;
        if (en.hasMoreElements()) {
            keyAlias = (String) en.nextElement();
        }

        return (PrivateKey) ks.getKey(keyAlias, nPassword);
    }

    public static void main(String[] args) throws Exception {
        RsaAlgorithm.getPrivateKey("E://rsa","123456");
    }
}
